<?php
//	  PHPcongrats - Holiday and Birthday Mailer
//	
//    Copyright (C) 2011  Matthias Nass
//
//    This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.


session_start();

if ($_SESSION['loggedin'] == true){
	include "./DBconnect.php";
	$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."';";
	$result = mysql_db_query($database, $query,$link);
	$result_row = mysql_fetch_row($result);
	if ($result_row != null){
		mysql_close($link);
		$_SESSION['message'] = "Benutzername schon vorhanden";
		$location_to_jump = "Location: http:./useradd.php";
		header( $location_to_jump );
	}
	elseif ($_POST['firstname'] == "" || $_POST['lastname'] == "" ||
	$_POST['password1'] == "" || $_POST['email'] == "" ||
	$_POST['password2'] == "" || $_POST['username'] == ""){
		mysql_close($link);
		$_SESSION['message'] = "Nicht alle Felder ausgef&uuml;llt";
		$location_to_jump = "Location: http:./useradd.php";
		header( $location_to_jump );
	}
	elseif ($_POST['password1'] == $_POST['password2']){
		include "./hash.php";
		$saltedHash = saltTheHash($_POST['password1']);

		$query = "INSERT INTO users VALUES(null,'".mysql_real_escape_string($_POST['firstname'])."'
					, '".mysql_real_escape_string($_POST['lastname'])."'
					, '".mysql_real_escape_string($_POST['username'])."'
					, '".mysql_real_escape_string($_POST['email'])."'
					, '".$saltedHash."'
					, CURRENT_TIMESTAMP 
					, CURRENT_TIMESTAMP);";

		$result = mysql_db_query($database, $query, $link);
		mysql_close($link);
		if ($result != false){
			$_SESSION['message'] = "Benutzer angelegt";
			$location_to_jump = "Location: http:./users.php";
			header( $location_to_jump );
		}
		else{
			$_SESSION['message'] = "Datenbankfehler";
			$location_to_jump = "Location: http:./users.php";
			header( $location_to_jump );
		}
	}
	else{
		mysql_close($link);
		$_SESSION['message'] = "Passw&ouml;rter stimmen nicht &uuml;berein";
		$location_to_jump = "Location: http:./useradd.php";
		header( $location_to_jump );
	}

} else{
	$_SESSION['last_location'] = "./useradd.php";
	header( 'Location: http:./login.php' );
}
?>
